package controllers

import (
	"errors"
	"github.com/gin-gonic/gin"
	"meituan/apps/shop/forms"
	"meituan/apps/shop/models"
	db2 "meituan/db"
	"meituan/utils/page"
	"meituan/utils/response"
	"strconv"
)

func QueryActivity(ctx *gin.Context) {
	form := forms.NewQueryActivityForm()
	ctx.ShouldBindQuery(form)

	db, _ := db2.NewDB()
	defer db.Close()

	query := db.Model(&models.Activity{}).Where("end_time > ?", form.EndTime)
	result := make([]models.Activity, 10)
	if form.ShopID != 0 {
		query = query.Where("shop_id = ? ", form.ShopID)
	}
	if form.Status != 0 {
		query = query.Where("status = ?", form.Status)
	}

	total, current, _ := page.Pagination(query, ctx.DefaultQuery("current", "1"), &result)
	ctx.JSON(200, gin.H{
		"code": 200,
		"data": result,
		"page": map[string]interface{}{
			"current": current,
			"total":   total,
		},
	})
}

func DeleteActivity(ctx *gin.Context) {
	id := ctx.Param("id")
	if num, e := strconv.Atoi(id); e != nil {
		response.SendError(ctx, errors.New("未找到对象"), 404)
		return
	} else {
		db, _ := db2.NewDB()
		defer db.Close()
		activity := &models.Activity{}
		activity.ID = uint(num)
		db.Model(activity).Delete(activity)
		ctx.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
	}

}

func UpdateActivity(ctx *gin.Context) {
	id := ctx.Param("id")
	if num, e := strconv.Atoi(id); e != nil {
		response.SendError(ctx, errors.New("未找到对象"), 404)
		return
	} else {
		form := models.NewActivity()
		if err := ctx.ShouldBindJSON(form); err != nil {
			response.SendError(ctx, err, 400)
			return
		}
		db, _ := db2.NewDB()
		defer db.Close()
		db.Model(&models.Activity{}).Where("id = ?", num).Update(form)
		ctx.JSON(200, gin.H{
			"code": 200,
			"data": form,
		})
	}
}

func CreateActivity(ctx *gin.Context) {
	form := models.NewActivity()
	if err := ctx.ShouldBindJSON(form); err != nil {
		response.SendError(ctx, err, 400)
		return
	}
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(&models.Activity{}).Create(form)
	ctx.JSON(200, gin.H{
		"code": 200,
		"data": form,
	})
}
